package com.yzc.android.network.base;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.yzc.android.utils.LogUtils;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by yzc on 16/2/1.
 */
public class KDJsonArrayRequest extends KDBaseRequest<JSONArray> {

    public KDJsonArrayRequest(int method,
                              Map<String, String> params,
                              Response.Listener<JSONArray> listener,
                              Response.ErrorListener errorListener) {
        super(method, null, params, listener, errorListener);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            Response<JSONArray> jsonResponse = Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
            try {
                try {
                    String paramJson = gson.toJson(getParams());
                    LogUtils.t(loggerTag).d("method=%s%nparams=%s%nresponse=%s", getUrl(), paramJson, gson.toJson(jsonResponse.result));
                }
                catch (Exception e)
                {
                    LogUtils.t(loggerTag).d("method=%s%nresponse=%s", getUrl(), gson.toJson(jsonResponse.result));
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return jsonResponse;
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    /**
     * @deprecated Use {@link #getBodyContentType()}.
     */
    @Override
    public String getPostBodyContentType() {
        return getBodyContentType();
    }

    /**
     * @deprecated Use {@link #getBody()}.
     */
    @Override
    public byte[] getPostBody() {
        return getBody();
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
}
